package org.jsola.hr.service.impl;

import org.jsola.admin.vo.SiteVO;
import org.jsola.core.Page;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.common.ExcelKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.ISaleUserDAO;
import org.jsola.hr.dto.SaleUserAddDTO;
import org.jsola.hr.dto.SaleUserUpdateDTO;
import org.jsola.hr.dto.permission.HrGroupAddDTO;
import org.jsola.hr.dto.permission.HrGroupUpdateDTO;
import org.jsola.hr.entity.CompanySaleUserDO;
import org.jsola.hr.entity.SaleUserDO;
import org.jsola.hr.provider.IAdminProviderService;
import org.jsola.hr.provider.IPermissionProviderService;
import org.jsola.hr.provider.IUserProviderService;
import org.jsola.hr.query.SaleUserQuery;
import org.jsola.hr.service.ICompanySaleUserService;
import org.jsola.hr.service.ISaleUserService;
import org.jsola.hr.vo.CompanyVO;
import org.jsola.hr.vo.HrGroupListVO;
import org.jsola.hr.vo.SaleUserListVO;
import org.jsola.hr.vo.SaleUserVO;
import org.jsola.permission.constant.PermissionConstants;
import org.jsola.permission.dto.GroupAddDTO;
import org.jsola.permission.dto.GroupUpdateDTO;
import org.jsola.permission.entity.GroupDO;
import org.jsola.permission.entity.GroupUserDO;
import org.jsola.permission.query.GroupQuery;
import org.jsola.permission.vo.BuildParentGroupListVO;
import org.jsola.permission.vo.GroupListVO;
import org.jsola.permission.vo.GroupVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.entity.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import static org.jsola.hr.constant.HrConstants.SITE_LEVER;
import static org.jsola.hr.constant.HrPermissionConstants.HR_DEFAULT_SUBJECT_ID;
import static org.jsola.hr.constant.HrPermissionConstants.SYSTEM_SUBJECT_TYPE;

/**
 * 销售人员
 *
 * @author zhr
 */
@Service("hrSaleUserServiceImpl")
public class SaleUserServiceImpl implements ISaleUserService {

    @Autowired
    private ISaleUserDAO saleUserDAO;

    @Autowired
    private ICompanySaleUserService companySaleUserService;

    @Autowired
    private IPermissionProviderService permissionProviderService;

    @Autowired
    private IAdminProviderService adminProviderService;

    @Autowired
    private IUserProviderService userProviderService;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public SaleUserVO save(SaleUserAddDTO saleUserAddDTO, TokenUser tokenUser) {
        // 转DO
        SaleUserDO saleUserDO = saleUserAddDTO.to(SaleUserDO.class);
        SaleUserDO saleUser = this.selectByUserId(saleUserAddDTO.getSaleUserId(), tokenUser);
        if (!ObjectUtils.isEmpty(saleUser)) {
            GroupDO group = permissionProviderService.selectGroupById(saleUser.getSaleGroupId(), tokenUser);
            throw new ParamException("该销售已存在分组名为[" + group.getName() + "]的分组下");
        }
        // 保存
        saleUserDO = save(saleUserDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return saleUserDO.to(SaleUserVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(SaleUserUpdateDTO saleUserUpdateDTO, TokenUser tokenUser) {
        //转DO
        SaleUserDO saleUserDO = saleUserUpdateDTO.to(SaleUserDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(saleUserDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... saleUserIds) {
        for (String saleUserId : saleUserIds) {
            SaleUserDO saleUser = selectDOById(saleUserId, tokenUser.getSiteId());
            List<CompanyVO> companyList = companySaleUserService
                    .selectCompanyBySaleUserId(saleUser.getSaleUserId(), tokenUser);
            if (!CollectionUtils.isEmpty(companyList)) {
                throw new ParamException("销售已绑定用工单位,请先在用工单位详情页内取消绑定");
            }
        }
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) saleUserIds);
    }


    @Override
    public SaleUserVO selectById(String saleUserId, String siteId) {
        SaleUserDO saleUserDO = selectDOById(saleUserId, siteId);
        if (saleUserDO == null) {
            return null;
        }
        return saleUserDO.to(SaleUserVO.class);
    }

    @Override
    public List<SaleUserListVO> select(SaleUserQuery saleUserQuery, String siteId) {
        List<SaleUserDO> saleUserDOList = selectDO(saleUserQuery, siteId);
        if (CollectionUtils.isEmpty(saleUserDOList)) {
            return saleUserDOList == null ? null : new ArrayList<>();
        }
        return saleUserDOList.stream()
                .map(saleUserDO -> saleUserDO.to(SaleUserListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(SaleUserQuery saleUserQuery, String siteId) {
        Example example = buildExample(saleUserQuery, siteId);
        return saleUserDAO.selectCountByExample(example);
    }

    @Override
    public Page<SaleUserListVO> selectPage(SaleUserQuery saleUserQuery, TokenUser tokenUser) {
        Example example = buildExample(saleUserQuery, tokenUser.getSiteId());
        Page<SaleUserDO> page = saleUserDAO.selectPageByExample(example,
                saleUserQuery.getPageNo(),
                saleUserQuery.getPageSize());

        Page<SaleUserListVO> result = page.to(SaleUserListVO.class);
        List<SaleUserListVO> entities = result.getEntities();
        for (SaleUserListVO saleUser : entities) {
            GroupDO group = permissionProviderService.selectGroupById(saleUser.getSaleGroupId(), tokenUser);
            saleUser.setGroupName(group.getName());
            List<CompanyVO> companyList = companySaleUserService
                    .selectCompanyBySaleUserId(saleUser.getSaleUserId(), tokenUser);
            if (!CollectionUtils.isEmpty(companyList)) {
                List<String> companyNameList = companyList.stream().map(CompanyVO::getName).collect(Collectors.toList());
                saleUser.setCompanyName(String.join(",", companyNameList));
                saleUser.setCompanyCount(companyNameList.size());
            }
        }
        return result;
    }

    @Override
    public SaleUserDO selectDOById(String saleUserId, String siteId) {
        return listById(saleUserId, siteId);
    }

    @Override
    public List<SaleUserDO> selectDO(SaleUserQuery saleUserQuery, String siteId) {
        Example example = buildExample(saleUserQuery, siteId);
        return saleUserDAO.selectByExample(example);
    }

    @Override
    public List<SaleUserDO> selectBySaleUserIdList(List<String> saleUserIdList, TokenUser tokenUser) {
        Example example = new Example(SaleUserDO.class);
        example.and().andIn("saleUserId", saleUserIdList)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId());
        return saleUserDAO.selectByExample(example);
    }

    @Override
    public List<GroupListVO> selectGroupTree(String groupOrAdminName, TokenUser tokenUser) {
        SiteVO site = adminProviderService.selectSiteById(tokenUser.getSiteId(), tokenUser);
        //获取首位超级管理员的user
        String userId = permissionProviderService.findMemberIdBySubject(PermissionConstants.ROLE_MEMBER_TYPE_USER,
                SYSTEM_SUBJECT_TYPE, HR_DEFAULT_SUBJECT_ID, tokenUser.getSiteId());
        UserDO userDO = userProviderService.selectUserById(userId);
        GroupQuery groupQuery = new GroupQuery();
        groupQuery.setGroupOrAdminName(groupOrAdminName);
        groupQuery.setGroupType("sale");
        groupQuery.setSiteName(site.getName());
        groupQuery.setSuperUser(userDO.getId());
        List<GroupListVO> groupTreeList = permissionProviderService.selectGroupTree(groupQuery, tokenUser);
        List<String> siteGroupAdmin = permissionProviderService.selectSiteGroupUser("sale", tokenUser.getSiteId());
        Boolean adminUser = tokenUser.getUserId().equals(userId) || siteGroupAdmin.contains(tokenUser.getUserId());
        assignmentMemberCount(groupTreeList, adminUser, tokenUser);
        return groupTreeList;
    }

    @Override
    public List<UserDO> selectAdminByGroupId(String groupId) {
        List<UserDO> result = new ArrayList<>();
        List<GroupUserDO> groupUserList = permissionProviderService.selectUserByGroupId(groupId);
        if (!CollectionUtils.isEmpty(groupUserList)) {
            List<String> userIdList = groupUserList.stream().map(GroupUserDO::getUserId).collect(Collectors.toList());
            result = userProviderService.selectUserByIds(userIdList);
        }
        return result;
    }

    @Override
    public Page<SaleUserListVO> selectSaleByGroupId(SaleUserQuery saleUserQuery, TokenUser tokenUser) {
        ParamException.notNull(saleUserQuery.getGroupId(), "请选择分组");
        GroupDO group = permissionProviderService.selectGroupById(saleUserQuery.getGroupId(), tokenUser);
        ParamException.notNull(group, "选择的分组不存在或已被删除");
        //获取首位超级管理员的user
        String userId = permissionProviderService.findMemberIdBySubject(PermissionConstants.ROLE_MEMBER_TYPE_USER,
                SYSTEM_SUBJECT_TYPE, HR_DEFAULT_SUBJECT_ID, tokenUser.getSiteId());
        // 如果不是超级管理员需要判断权限
        if (!tokenUser.getUserId().equals(userId)) {
            // 查询当前登录用户是否在销售分组内有管理员身份
            List<GroupUserDO> groupUser = permissionProviderService.selectGroupCurrentUser("sale", tokenUser);
            List<String> groupIdList = groupUser.stream().map(GroupUserDO::getGroupId).collect(Collectors.toList());
            permissionProviderService.filterGroupId(groupIdList, tokenUser.getSiteId());
            if (CollectionUtils.isEmpty(groupIdList)) {
                return new Page<>(saleUserQuery.getPageSize(), saleUserQuery.getPageNo());
            }
            List<String> childGroupIdList = permissionProviderService
                    .selectGroupByIdByParent(groupIdList, tokenUser.getSiteId());
            List<String> distinctList = childGroupIdList.stream().distinct().collect(Collectors.toList());
            // 如果是租户级别分组把所有有权限的组合起来分页查询
            if (SITE_LEVER.equals(group.getLevel())) {
                saleUserQuery.setGroupIdList(distinctList);
                return selectPage(saleUserQuery, tokenUser);
            }
            // 如果不是租户级别分组则查询对应管理员所在分组的上级分组
            List<BuildParentGroupListVO> buildParentGroupList = permissionProviderService
                    .buildParentGroupList(groupIdList, "sale", tokenUser);
            // 如果筛选条件筛选到了对应分组的上级分组则显示对应分组的所有数据
            for (BuildParentGroupListVO buildParentGroup : buildParentGroupList) {
                List<String> parentGroupIdList = buildParentGroup.getParentGroupIdList();
                if (parentGroupIdList.contains(saleUserQuery.getGroupId())) {
                    List<String> selectGroupIdList = permissionProviderService.selectGroupByIdByParent
                            (Collections.singletonList(buildParentGroup.getGroupId()), tokenUser.getSiteId());
                    saleUserQuery.setGroupIdList(selectGroupIdList);
                    return selectPage(saleUserQuery, tokenUser);
                }
            }
            // 走到这里说明没有筛选到上级分组
            List<String> queryGroupIdList = this
                    .selectGroupIdByIsCurrent(saleUserQuery.getIsCurrentGroup(), saleUserQuery.getGroupId(), tokenUser);
            saleUserQuery.setGroupIdList(queryGroupIdList);
            return selectPage(saleUserQuery, tokenUser);
        }
        List<String> queryGroupIdList = this
                .selectGroupIdByIsCurrent(saleUserQuery.getIsCurrentGroup(), saleUserQuery.getGroupId(), tokenUser);
        saleUserQuery.setGroupIdList(queryGroupIdList);
        return selectPage(saleUserQuery, tokenUser);
    }

    @Override
    public String exportSale(SaleUserQuery saleUserQuery, TokenUser tokenUser) {
        GroupDO group = permissionProviderService.selectGroupById(saleUserQuery.getGroupId(), tokenUser);
        ParamException.notNull(group, "选择的分组不存在或已被删除");
        //获取首位超级管理员的user
        String userId = permissionProviderService.findMemberIdBySubject(PermissionConstants.ROLE_MEMBER_TYPE_USER,
                SYSTEM_SUBJECT_TYPE, HR_DEFAULT_SUBJECT_ID, tokenUser.getSiteId());
        if (tokenUser.getUserId().equals(userId)) {
            List<String> queryGroupIdList = this
                    .selectGroupIdByIsCurrent(saleUserQuery.getIsCurrentGroup(), saleUserQuery.getGroupId(), tokenUser);
            saleUserQuery.setGroupIdList(queryGroupIdList);
        } else {
            // 查询当前登录用户是否在销售分组内有管理员身份
            List<GroupUserDO> groupUser = permissionProviderService.selectGroupCurrentUser("sale", tokenUser);
            List<String> groupIdList = groupUser.stream().map(GroupUserDO::getGroupId).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(groupIdList)) {
                throw new ParamException("暂无数据可导出");
            }
            List<String> childGroupIdList = permissionProviderService
                    .selectGroupByIdByParent(groupIdList, tokenUser.getSiteId());
            List<String> distinctList = childGroupIdList.stream().distinct().collect(Collectors.toList());
            // 如果是租户级别分组把所有有权限的组合起来分页查询
            if (SITE_LEVER.equals(group.getLevel())) {
                saleUserQuery.setGroupIdList(distinctList);
            } else {
                // 如果不是租户级别分组则查询对应管理员所在分组的上级分组
                List<BuildParentGroupListVO> buildParentGroupList = permissionProviderService
                        .buildParentGroupList(groupIdList, "sale", tokenUser);
                // 如果筛选条件筛选到了对应分组的上级分组则导出对应分组的所有数据
                for (BuildParentGroupListVO buildParentGroup : buildParentGroupList) {
                    List<String> parentGroupIdList = buildParentGroup.getParentGroupIdList();
                    if (parentGroupIdList.contains(saleUserQuery.getGroupId())) {
                        List<String> selectGroupIdList = permissionProviderService.selectGroupByIdByParent
                                (Collections.singletonList(buildParentGroup.getGroupId()), tokenUser.getSiteId());
                        saleUserQuery.setGroupIdList(selectGroupIdList);
                    }
                }
            }
            // 走到这里分组Id还是为空说明也不是筛选的上级分组
            if (CollectionUtils.isEmpty(saleUserQuery.getGroupIdList())) {
                List<String> queryGroupIdList = this
                        .selectGroupIdByIsCurrent(saleUserQuery.getIsCurrentGroup(), saleUserQuery.getGroupId(), tokenUser);
                saleUserQuery.setGroupIdList(queryGroupIdList);
            }
        }
        Example example = buildExample(saleUserQuery, tokenUser.getSiteId());
        List<SaleUserDO> exportList = saleUserDAO.selectByExample(example);
        List<SaleUserListVO> list = new ArrayList<>();
        for (SaleUserDO saleUser : exportList) {
            SaleUserListVO sale = saleUser.to(SaleUserListVO.class);
            if (!StringUtils.isEmpty(sale.getRegion())) {
                String region = sale.getRegion();
                sale.setRegion(region.substring(region.indexOf("_") + 1));
            }
            GroupDO saleGroup = permissionProviderService.selectGroupById(saleUser.getSaleGroupId(), tokenUser);
            sale.setGroupName(saleGroup.getName());
            List<CompanyVO> companyList = companySaleUserService
                    .selectCompanyBySaleUserId(saleUser.getSaleUserId(), tokenUser);
            if (!CollectionUtils.isEmpty(companyList)) {
                List<String> companyNameList = companyList.stream().map(CompanyVO::getName).collect(Collectors.toList());
                sale.setCompanyName(String.join(",", companyNameList));
            }
            list.add(sale);
        }
        return ExcelKit.exportExcel("sale", "销售", SaleUserListVO.class, list);
    }

    @Override
    public List<SaleUserDO> selectSaleBySite(TokenUser tokenUser) {
        Example example = new Example(SaleUserDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId());
        return saleUserDAO.selectByExample(example);
    }

    @Override
    public SaleUserDO selectByUserId(String userId, TokenUser tokenUser) {
        Example example = new Example(SaleUserDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("saleUserId", userId)
                .andEqualTo("siteId", tokenUser.getSiteId());
        return saleUserDAO.selectOneByExample(example);
    }

    @Override
    public GroupVO saveGroup(HrGroupAddDTO hrGroupAddDTO, TokenUser tokenUser) {
        GroupAddDTO groupAddDTO = hrGroupAddDTO.to(GroupAddDTO.class);
        GroupVO result = permissionProviderService.saveGroup(groupAddDTO, tokenUser);
        // 保存完分组保存分组主管
        if (!CollectionUtils.isEmpty(hrGroupAddDTO.getGroupSupervisor())) {
            List<GroupUserDO> bachSaveList = new ArrayList<>();
            for (UserDO user : hrGroupAddDTO.getGroupSupervisor()) {
                bachSaveList.add(initGroupUser(user, result.getId(), tokenUser));
            }
            if (!CollectionUtils.isEmpty(bachSaveList)) {
                permissionProviderService.bachSaveGroupUser(bachSaveList, tokenUser);
            }
        }
        return result;
    }

    private GroupUserDO initGroupUser(UserDO user, String groupId, TokenUser tokenUser) {
        GroupUserDO groupUser = new GroupUserDO();
        groupUser.setUserId(user.getId());
        groupUser.setGroupId(groupId);
        groupUser.setGroupType("sale");
        groupUser.setUserName(user.getName());
        groupUser.preInsert(tokenUser.getUserId());
        groupUser.setSiteId(tokenUser.getSiteId());
        return groupUser;
    }

    @Override
    public void updateGroup(HrGroupUpdateDTO hrGroupUpdateDTO, TokenUser tokenUser) {
        GroupUpdateDTO groupUpdate = hrGroupUpdateDTO.to(GroupUpdateDTO.class);
        // 不能把当前编辑的分组的父级改成自己或者他的下级分组
        List<String> childGroupIdList = permissionProviderService
                .selectGroupByIdByParent(Collections.singletonList(hrGroupUpdateDTO.getId()), tokenUser.getSiteId());
        if (childGroupIdList.contains(hrGroupUpdateDTO.getParentId())) {
            throw new ParamException("不能把当前分组的父级改成自己或者他的下级分组");
        }
        GroupListVO siteGroup = permissionProviderService.selectSiteGroup("sale", tokenUser.getSiteId());
        //获取首位超级管理员的user
        String userId = permissionProviderService.findMemberIdBySubject(PermissionConstants.ROLE_MEMBER_TYPE_USER,
                SYSTEM_SUBJECT_TYPE, HR_DEFAULT_SUBJECT_ID, tokenUser.getSiteId());
        permissionProviderService.updateGroup(groupUpdate, tokenUser);
        permissionProviderService.deleteUserFromGroupId(hrGroupUpdateDTO.getId());
        if (!CollectionUtils.isEmpty(hrGroupUpdateDTO.getGroupSupervisor())) {
            List<GroupUserDO> bachSaveList = new ArrayList<>();
            for (UserDO user : hrGroupUpdateDTO.getGroupSupervisor()) {
                if (hrGroupUpdateDTO.getId().equals(siteGroup.getId()) && user.getId().equals(userId)) {
                    continue;
                }
                bachSaveList.add(initGroupUser(user, hrGroupUpdateDTO.getId(), tokenUser));
            }
            if (!CollectionUtils.isEmpty(bachSaveList)) {
                permissionProviderService.bachSaveGroupUser(bachSaveList, tokenUser);
            }
        }
    }

    @Override
    public void deleteGroup(String groupId, TokenUser tokenUser) {
        List<String> groupIdList = permissionProviderService
                .selectGroupByIdByParent(Collections.singletonList(groupId), tokenUser.getSiteId());
        Integer count = selectSaleCountByGroupIdList(groupIdList, tokenUser);
        if (count > 0) {
            throw new ParamException("分组或子分组下还存在销售人员");
        }
        permissionProviderService.deleteGroup(groupId, tokenUser);
    }

    @Override
    public GroupListVO selectDefaultGroupId(TokenUser tokenUser) {
        //获取首位超级管理员的user
        String userId = permissionProviderService.findMemberIdBySubject(PermissionConstants.ROLE_MEMBER_TYPE_USER,
                SYSTEM_SUBJECT_TYPE, HR_DEFAULT_SUBJECT_ID, tokenUser.getSiteId());
        List<String> userIdList = permissionProviderService
                .selectSiteGroupUser("sale", tokenUser.getSiteId());
        userIdList.add(userId);
        // 如果当前用户是当前租户创建人或者租户级别分组管理员，默认选中租户级别分组
        if (userIdList.contains(tokenUser.getUserId())) {
            GroupListVO groupSite = permissionProviderService.selectSiteGroup("sale", tokenUser.getSiteId());
            if(!ObjectUtils.isEmpty(groupSite)){
                return groupSite;
            }
            return null;
        } else {
            // 查询当前登录用户有权限的分组
            List<GroupUserDO> currentUserGroup = permissionProviderService
                    .selectGroupCurrentUser("sale", tokenUser);
            if(CollectionUtils.isEmpty(currentUserGroup)){
                return null;
            }
            List<String> groupIdList = currentUserGroup.stream()
                    .map(GroupUserDO::getGroupId).collect(Collectors.toList());
            List<GroupListVO> groupList = permissionProviderService.findGroupsByIds(groupIdList, tokenUser.getSiteId());
            groupList = groupList.stream().sorted(Comparator.comparing(GroupListVO::getLevel))
                    .collect(Collectors.toList());
            return groupList.get(0);
        }
    }

    @Override
    public HrGroupListVO selectGroupInfo(String groupId, TokenUser tokenUser) {
        List<GroupListVO> groupList = permissionProviderService
                .findGroupsByIds(Collections.singletonList(groupId), tokenUser.getSiteId());
        GroupListVO group = groupList.get(0);
        HrGroupListVO result = group.to(HrGroupListVO.class);
        List<GroupUserDO> groupUserList = permissionProviderService.selectUserByGroupId(groupId);
        List<UserDO> userList = new ArrayList<>();
        //获取首位超级管理员的user
        String userId = permissionProviderService.findMemberIdBySubject(PermissionConstants.ROLE_MEMBER_TYPE_USER,
                SYSTEM_SUBJECT_TYPE, HR_DEFAULT_SUBJECT_ID, tokenUser.getSiteId());
        if ("0".equals(result.getParentId())) {
            // 如果是租户级别分组
            result.setEditAdminPermissions(tokenUser.getUserId().equals(userId));
            UserDO userDO = userProviderService.selectUserById(userId);
            userList.add(userDO);
        } else {
            // 租户级别的管理员
            List<String> siteGroupUserId = permissionProviderService
                    .selectSiteGroupUser("sale", tokenUser.getSiteId());
            // 如果是超级管理员或者租户级别分组管理员直接赋值有可以编辑分组管理员权限
            if (tokenUser.getUserId().equals(userId) || siteGroupUserId.contains(tokenUser.getUserId())) {
                result.setEditAdminPermissions(true);
            } else {
                // 查询当前登录用户有权限的分组
                List<GroupUserDO> groupUsers = permissionProviderService
                        .selectGroupCurrentUser("sale", tokenUser);
                List<String> groupIdList = groupUsers.stream()
                        .map(GroupUserDO::getGroupId).collect(Collectors.toList());
                permissionProviderService.filterGroupId(groupIdList, tokenUser.getSiteId());
                if (CollectionUtils.isEmpty(groupIdList)) {
                    // 没有分组管理员权限赋值无权限
                    result.setEditAdminPermissions(false);
                } else {
                    List<String> childGroupIdList = permissionProviderService
                            .selectGroupByIdByParent(groupIdList, tokenUser.getSiteId());
                    List<String> distinctList = childGroupIdList.stream().distinct()
                            .filter(id -> !groupIdList.contains(id)).collect(Collectors.toList());
                    result.setEditAdminPermissions(distinctList.contains(result.getId()));
                }
            }
        }
        if (!CollectionUtils.isEmpty(groupUserList)) {
            List<String> userIdList = groupUserList.stream().map(GroupUserDO::getUserId).collect(Collectors.toList());
            userList.addAll(userProviderService.selectUserByIds(userIdList));
        }
        result.setGroupSupervisor(userList);
        return result;
    }

    @Override
    public void updatePhone(String userId, String phone) {
        SaleUserDO saleUserDO = new SaleUserDO();
        saleUserDO.setSalePhone(phone);
        Example example = new Example(SaleUserDO.class);
        example.and().andEqualTo("saleUserId", userId)
                        .andEqualTo("valid", true);
        saleUserDAO.updateByExampleSelective(saleUserDO, example);
    }

    /**
     * 根据筛选条件查询分组Id
     */
    private List<String> selectGroupIdByIsCurrent(Boolean isCurrentGroup, String groupId, TokenUser tokenUser) {
        List<String> groupIdList;
        if (isCurrentGroup) {
            groupIdList = Collections.singletonList(groupId);
        } else {
            groupIdList = permissionProviderService.selectGroupByIdByParent(
                    Collections.singletonList(groupId), tokenUser.getSiteId()
            );
        }
        return groupIdList;
    }

    /**
     * 赋值成员数量
     */
    private void assignmentMemberCount(List<GroupListVO> groupTree, Boolean adminUser, TokenUser tokenUser) {
        // 查询当前登录用户是否在销售分组内有管理员身份
        List<GroupUserDO> groupUser = permissionProviderService.selectGroupCurrentUser("sale", tokenUser);
        List<String> groupIdList = groupUser.stream().map(GroupUserDO::getGroupId).collect(Collectors.toList());
        permissionProviderService.filterGroupId(groupIdList, tokenUser.getSiteId());
        for (GroupListVO group : groupTree) {
            if (CollectionUtils.isEmpty(group.getChildList())) {
                if (SITE_LEVER.equals(group.getLevel())) {
                    // 如果是租户级分组
                    if (adminUser) {
                        List<String> childGroupIdList = permissionProviderService
                                .selectGroupByIdByParent(Collections.singletonList(group.getId()), tokenUser.getSiteId());
                        group.setMemberCount(selectSaleCountByGroupIdList(childGroupIdList, tokenUser));
                    } else {
                        group.setMemberCount(selectSaleCountByGroupIdList(groupIdList, tokenUser));
                    }
                } else {
                    group.setMemberCount(selectSaleCountByGroupIdList(Collections.singletonList(group.getId()), tokenUser));
                }
            } else {
                // 这边也要分是否是租户级分组
                if (SITE_LEVER.equals(group.getLevel())) {
                    if (adminUser) {
                        List<String> childGroupIdList = permissionProviderService
                                .selectGroupByIdByParent(Collections.singletonList(group.getId()), tokenUser.getSiteId());
                        group.setMemberCount(selectSaleCountByGroupIdList(childGroupIdList, tokenUser));
                        assignmentMemberCount((List<GroupListVO>) group.getChildList(), true, tokenUser);
                    } else {
                        List<String> childGroupIdList = permissionProviderService
                                .selectGroupByIdByParent(groupIdList, tokenUser.getSiteId());
                        group.setMemberCount(selectSaleCountByGroupIdList(childGroupIdList, tokenUser));
                        assignmentMemberCount((List<GroupListVO>) group.getChildList(), false, tokenUser);
                    }
                } else {
                    if (adminUser) {
                        List<String> childGroupIdList = permissionProviderService
                                .selectGroupByIdByParent(Collections.singletonList(group.getId()), tokenUser.getSiteId());
                        group.setMemberCount(selectSaleCountByGroupIdList(childGroupIdList, tokenUser));
                        assignmentMemberCount((List<GroupListVO>) group.getChildList(), true, tokenUser);
                    } else {
                        // 查询对应管理员所在分组的上级分组
                        List<BuildParentGroupListVO> buildParentGroupList = permissionProviderService
                                .buildParentGroupList(groupIdList, "sale", tokenUser);
                        boolean up = false;
                        for (BuildParentGroupListVO buildParentGroup : buildParentGroupList) {
                            List<String> parentGroupIdList = buildParentGroup.getParentGroupIdList();
                            if (parentGroupIdList.contains(group.getId())) {
                                List<String> childGroupIdList = permissionProviderService.selectGroupByIdByParent
                                        (Collections.singletonList(buildParentGroup.getGroupId()), tokenUser.getSiteId());
                                group.setMemberCount(selectSaleCountByGroupIdList(childGroupIdList, tokenUser));
                                assignmentMemberCount((List<GroupListVO>) group.getChildList(), false, tokenUser);
                                up = true;
                            }
                        }
                        if (!up) {
                            List<String> childGroupIdList = permissionProviderService
                                    .selectGroupByIdByParent(Collections.singletonList(group.getId()), tokenUser.getSiteId());
                            group.setMemberCount(selectSaleCountByGroupIdList(childGroupIdList, tokenUser));
                            assignmentMemberCount((List<GroupListVO>) group.getChildList(), false, tokenUser);
                        }
                    }
                }
            }
        }
    }

    /**
     * 查询对应销售分组下的销售人员数量
     */
    private Integer selectSaleCountByGroupIdList(List<String> groupIdList, TokenUser tokenUser) {
        if(CollectionUtils.isEmpty(groupIdList)){
            return 0;
        }
        Example example = new Example(SaleUserDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId())
                .andIn("saleGroupId", groupIdList);
        return saleUserDAO.selectCountByExample(example);
    }

    /**
     * 根据查询参数，构建example
     *
     * @param saleUserQuery 查询参数
     * @param siteId        所属站点id
     * @return example
     */
    private Example buildExample(SaleUserQuery saleUserQuery, String siteId) {
        Example example = new Example(SaleUserDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (!StringUtils.isEmpty(saleUserQuery.getSaleNameOrPhoneOrIdCard())) {
            example.and()
                    .orLike("saleName", "%" + saleUserQuery.getSaleNameOrPhoneOrIdCard() + "%")
                    .orLike("salePhone", "%" + saleUserQuery.getSaleNameOrPhoneOrIdCard() + "%")
                    .orLike("saleIdCard", "%" + saleUserQuery.getSaleNameOrPhoneOrIdCard() + "%");
        }
        if (!CollectionUtils.isEmpty(saleUserQuery.getGroupIdList())) {
            example.and().andIn("saleGroupId", saleUserQuery.getGroupIdList());
        }
        if (!StringUtils.isEmpty(saleUserQuery.getRegion())) {
            String areaName = adminProviderService.selectAreaById(saleUserQuery.getRegion());
            example.and()
                    .orLike("region", "%" + areaName + "%");
        }
        // 排序
        ExampleKit.setExampleOrder(example, saleUserQuery.getOrders());
        return example;
    }
}




